package com.lt.common;

import android.os.Handler;

public class ltTimer {
    private Handler timer = new Handler();
    private int secondsPassed = 0;
    private long delayMillis = 1000;
    private ltTimerListener listener;

    /**
     * 开始定时器
     *
     * @param listener     监听
     * @param initialDelay 延迟执行的时间
     * @param period       执行间隔时间
     */
    public void startTimer(ltTimerListener listener,
                           long initialDelay,
                           long period) {
        this.listener = listener;
        this.delayMillis = period;
        if (secondsPassed == 0) {
            timer.removeCallbacks(updateTimeElasped);
            // tell timer to run call back after 1 second
            timer.postDelayed(updateTimeElasped, initialDelay);
        }
    }

    /**
     * 停止定时器
     */
    public void stopTimer() {
        // disable call backs
        listener = null;
        secondsPassed = 0;
        timer.removeCallbacks(updateTimeElasped);
    }

    // timer call back when timer is ticked
    private final Runnable updateTimeElasped = new Runnable() {
        public void run() {
//            long currentMilliseconds = System.currentTimeMillis();
            ++secondsPassed;
            // add notification

            // 执行操作
            if (listener != null) {
                listener.onTimerRun(ltTimer.this);
            }

            /*
             *postAtTime这句函数有点问题
             *多次运行，有可能造成执行慢，执行时间长达200ms+
             *造成主线程卡顿
             */
            //timer.postAtTime(this, currentMilliseconds);
            // notify to call back after 1 seconds
            // basically to remain in the timer loop
            timer.postDelayed(updateTimeElasped, delayMillis);

        }
    };

    /**
     * 修改timer的工作间隔
     */
    public void updateDelayMillis(int period) {
        this.delayMillis = period;
    }

    public interface ltTimerListener {
        void onTimerRun(ltTimer timer);
    }
}
